<?php
	class utility
	{
		function addAnnouncement($subject,$desc,$cats,$image,$uid,$when)
		{
			if($image['name'] != '')
			{
				$img		= "site/images/uploads/".str_replace(' ','_',$image['name']);
				$image_path	= trim($_SERVER['DOCUMENT_ROOT'],'/')."/bizbuddy.com/".$img;
				if(!move_uploaded_file($image['tmp_name'],$image_path))
				{
					utility::redirect('/bizbuddy.com','Error Uploading Image');
					return;
				}
				$image_path	= $img;
			}
			else
				$image_path = '';
			$sql = "INSERT INTO announcement(`name`,description,category_ids,`image`,user_id,`when`)
					VALUES('$subject','$desc','$cats','$image_path',$uid,'$when')";
			if(utility::mQuery($sql))
			{
				utility::redirect('/bizbuddy.com','Your Announcement Has Been Added!');
				return true;
			}
			else
			{
				utility::redirect('/bizbuddy.com','Error Occured');
				return false;
			}			
		}
		function editAnnouncement($subject,$desc,$cats,$oldImage,$image,$when,$status,$id)
		{
			if($image['name'] != '')
			{
				$img		= "site/images/uploads/".str_replace(' ','_',$image['name']);
				$image_path	= trim($_SERVER['DOCUMENT_ROOT'],'/')."/bizbuddy.com/".$img;
				if(!move_uploaded_file($image['tmp_name'],$image_path))
				{
					utility::redirect('/bizbuddy.com','Error Uploading Image');
					return;
				}
				$image_path	= $img;
				unlink(trim($_SERVER['DOCUMENT_ROOT'],'/')."/bizbuddy.com/".$oldImage);
			}
			else
				$image_path = $oldImage;
			$sql = "UPDATE announcement
					SET `name` = \"$subject\",
						description = \"$desc\",
						category_ids = \"$cats\",
						`image` = \"$image_path\",
						`last_when` = \"$when\",
						`status` = $status
					WHERE id = $id
					";
			if(utility::mQuery($sql))
			{
				utility::redirect('/bizbuddy.com','Your Announcement Has Been Updated!');
				return true;
			}
			else
			{
				utility::redirect('/bizbuddy.com','Error Occured');
				return false;
			}
		}
		
		function addBusiness($name,$desc,$cats,$image,$uid,$when,$person,$phone,$email,$www,$address)
		{
			$root_path 	= $_SERVER['DOCUMENT_ROOT'];
			if($image['name'] != '')
			{
				$image_path	= $root_path."bizbuddy.com/site/images/uploads/".$image['name'];
				if(!move_uploaded_file($image['tmp_name'],$image_path))
				{
					utility::redirect('/bizbuddy.com','Error Uploading Image');
					return;
				}
			}
			else
				$image_path = '';
			$sql = "INSERT INTO business (`name`, description, category_ids, `image`, user_id, `when`, `person`, phone, email, website, address)
				VALUES('$name','$desc','$cats','$image_path',$uid,'$when','$person','$phone','$email','$www','$address')";
			if(utility::mQuery($sql))
			{
				utility::redirect('/bizbuddy.com','Your Business Profile Has Been Added!');
				return true;
			}
			else
			{
				utility::redirect('/bizbuddy.com','Error Occured');
				return false;
			}			
		}
		
		function editBusiness($name,$desc,$cats,$oldImage,$image,$when,$person,$phone,$email,$www,$address,$status,$id)
		{
			if($image['name'] != '')
			{
				$img		= "site/images/uploads/".str_replace(' ','_',$image['name']);
				$image_path	= trim($_SERVER['DOCUMENT_ROOT'],'/')."/bizbuddy.com/".$img;
				if(!move_uploaded_file($image['tmp_name'],$image_path))
				{
					utility::redirect('/bizbuddy.com','Error Uploading Image');
					return;
				}
				$image_path	= $img;
				unlink(trim($_SERVER['DOCUMENT_ROOT'],'/')."/bizbuddy.com/".$oldImage);
			}
			else
				$image_path = $oldImage;
			$sql = "UPDATE business
					SET `name` = \"$name\",
						description = \"$desc\",
						category_ids = \"$cats\",
						`image` = \"$image_path\",
						`last_when` = \"$when\",
						`person` = \"$person\",
						phone = \"$phone\",
						email = \"$email\",
						website = \"$www\",
						address = \"$address\",
						`status` = $status
					WHERE id = $id
					";
			if(utility::mQuery($sql))
			{
				utility::redirect('/bizbuddy.com','Your Business Profile Has Been Updated!');
				return true;
			}
			else
			{
				utility::redirect('/bizbuddy.com','Error Occured');
				return false;
			}
		}
		
		function addUser($name,$email,$number,$sex,$password,$when)
		{		
			$sql = "INSERT INTO user(`name`,email,phone,sex,password,`when`) 
					VALUES('$name','$email','$number','$sex','$password','$when')";
			if(utility::mQuery($sql))
			{
				$msg = "Congratulation! You have successfully registered.";
			}
			else
			{
				$msg = "Error Occured!";
			}
			utility::redirect('/bizbuddy.com',$msg);
		}
		
		function editUser($name,$email,$number,$sex,$password,$when,$id,$status)
		{
			$sql = "UPDATE user
					SET `name` = \"$name\",
						email = \"$email\",
						phone = \"$number\",
						sex = \"$sex\",
						password = \"$password\",
						`last_when` = \"$when\",
						status = $status
					WHERE id = $id";
			var_dump($sql);
			if(utility::mQuery($sql))
			{
				$msg = "User has been successfully updated.";
			}
			else
			{
				$msg = "Error Occured!";
			}
			utility::redirect('/bizbuddy.com',$msg);
		}
		
		function signin($name,$password)
		{
			$user = utility::getUser($name);
			if($user[0]['name'] == $name && $user[0]['password'] == $password)
			{
				$msg		= 'Logged in!';
				if($name == 'bliss')
				{
					$_SESSION['admin'] = 'thea7y';
					utility::redirect('/bizbuddy.com/admin.php',$msg);
				}
				else
					utility::redirect('/bizbuddy.com',$msg);
				$_SESSION['user_name'] 	= $name;
				$_SESSION['user_id']	= $user[0]['id'];
				//setcookie('user_name',$name,time() + 86400); // 86400 = 1 day
				//setcookie('user_pw',$password,time() + 86400);
			}
			else
			{
				$msg		= 'Wrong user Name or Password';
				utility::redirect('/bizbuddy.com',$msg);
			}
		}
		
		// get all users
		function getUsers()
		{
			$sql = "SELECT * FROM user ORDER BY `status`,`when` DESC";
			return utility::sQuery($sql);
		}
		
		// get a user's data
		function getUser($name)
		{
			$sql = "SELECT * FROM user WHERE UPPER(`name`) = UPPER('$name') AND status = 1";
			return utility::sQuery($sql);
		}
		
		// get data from database
		function sQuery($sql)
		{
			$res = array();
			if ( !$dbh  = mysql_connect('localhost', 'root', '')) 
			{
    			return "Can't connect: ".mysql_error();
			}		
			if(!mysql_select_db("bizbuddy", $dbh))
			{
				return 'Cannot Select Database';
			}
			if(! $result = mysql_query($sql,$dbh))
			{
				$res = null;
			}
			else
			{
				if($result == null)
				{
					return null;
				}
				while($each = mysql_fetch_array($result))
				{
					$res[] = $each;
				}
			}
			mysql_close($dbh);
			return $res;
		}
		
		// modify database
		function mQuery($sql)
		{
			if ( !$dbh  = mysql_connect('localhost', 'root', '')) 
			{
    			die("Can't connect: ".mysql_error());
			}		
			if(!mysql_select_db("bizbuddy", $dbh))
			{
				echo 'Cannot Select Database';
			}
			if(!mysql_query($sql,$dbh))
			{
				mysql_close($dbh);
				return false;
			}
			else
			{
				mysql_close($dbh);
				return true;
			}

		}
				
		//this is when wanting to redirect to homepage :D
		function redirect($url,$msg)
		{
			header("Location: $url");
			//setcookie('msg',$msg,time()+100);
			$_SESSION['msg'] = $msg;
		}
		
		// add new category
		function addCat($newCat,$when)
		{
			$sql = "INSERT INTO category(`name`,`when`) VALUES('$newCat','$when')";
			utility::mQuery($sql);
		}
		
		//get All Categories
		function getCats()
		{
			$sql = "SELECT * FROM category ORDER BY `name`";
			return utility::sQuery($sql);
		}
                
		function countByCat($cat_id,$type)
		{
				$sql = "SELECT count(*) as total FROM $type WHERE category_ids LIKE '%$cat_id,%'";
				return utility::sQuery($sql);
		}
		
		//get Posts by Category
		function getPostsByCat($cat_id,$type)
		{
			$sql = "SELECT * FROM $type WHERE category_ids LIKE '%$cat_id,%' ORDER BY `name`";
			return utility::sQuery($sql);
		}
		
		//get all posts
		function getAllPosts($type)
		{
			$sql = "SELECT * FROM $type ORDER BY `status`,`when` DESC";
			return utility::sQuery($sql);
		}
		
		//get all posts by user
		function getUserPosts($type,$uid)
		{
			$sql = "SELECT * FROM $type WHERE user_id = $uid ORDER BY `status`,`when` DESC";
			return utility::sQuery($sql);
		}
		
		//get all approved posts
		function getPosts($type)
		{
			$sql = "SELECT * FROM $type WHERE `status` = 1 ORDER BY `when` DESC";
			return utility::sQuery($sql);
		}
		
		//get post
		function getPost($id,$type)
		{
			$sql = "SELECT * FROM $type WHERE id=$id";
			return utility::sQuery($sql);
		}
		
		//show single post
		function showContent($post)
		{ 
			echo '	<h2 align="center" id="title">'.$post['name'].'</h2><br/>
					<center><img src="'.$post['image'].'" id="bigThumbnail"/></center><br/>
					<p id="description">'.$post['description'].'
			';
		}
		
		//show suggestions for keyword
		function getSuggestions($keyword)
		{
			$sql = "SELECT `name` FROM announcement WHERE `name` LIKE '%$keyword%'";
			$suggestions = utility::sQuery($sql);
			echo '<ul>';
			foreach($suggestions as $suggestion)
			{
				echo '<li><a>'.$suggestion['name'].'</a></li>';
			}
			echo '</ul>';
		}
		
		//show results of search **** have to restrict value inputing 
		function getResults($keyword,$table_name)
		{
			include("../blocks/search.php");
			if($table_name == '3' || $table_name == '0')
			{
				$sql = "SELECT  * FROM (
						SELECT id,`name`,description,urls FROM announcement AS a WHERE a.name LIKE '%$keyword%' OR a.description LIKE '%$keyword%'
						UNION 
						SELECT id,`name`,description,urls FROM business AS b WHERE b.name LIKE '%$keyword%' OR b.description LIKE '%$keyword%'
						)as result";
			}
			else 
			{
				if($table_name == '1')
				{
					$table_name = 'announcement';
				}
				else
				{
					$table_name = 'business';
				}
				$sql = "SELECT * FROM $table_name WHERE `name` LIKE '%$keyword%' OR description LIKE '%$keyword%'";
			}
					
			$results = utility::sQuery($sql);
			//echo '<br/><br/><br/><br/><br/><br/><br/>';
			//var_dump($sql);
			if($results != null)
			{
				foreach($results as $result)
				{
					echo '	<div class="results">
								<a target="_blank" href="'.$result['urls'].$result['id'].'-'.str_replace(' ','_',$result['name']).'.php">'.$result['name'].'</a><br />
								<p>'.substr($result['description'],0,150).'...</p>
							</div>
					';
				}
			}
			else
				echo '<br/><center>No results found!</center>';
		}
		
		function approve($what,$from,$who)
		{
			$what = 1-$what;
			$sql = "UPDATE $from SET `status` = $what WHERE id = $who";
			utility::mQuery($sql);
			echo 'approved';
		}
		
		function edit($from,$who)
		{
			echo 'edited';
		}
		
		function delete($from,$who)
		{
			$sql = "DELETE FROM $from WHERE id = $who";
			utility::mQuery($sql);
			echo 'deleted';
		}
	}
?>